/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DownloadDetails.java
 *
 * Created on 09/11/2012, 19:07:40
 */
package views;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.table.AbstractTableModel;
import util.IncompleteFile;

/**
 *
 * @author Gravena
 */
public class DownloadDetails extends javax.swing.JFrame {

    private IncompleteFile file;
    private peersTableModel peers;
    private int parts;    

    public void addPeer(int index, String text) {
        peers.addItem(index, text);
    }

    public void updatePeer(int index, String text) {
        peers.updateItem(index, text);
    }

    public void removePeer(int index) {
        peers.removeIndex(index);
    }

    public void setVelocidade(String v) {
        this.valueVelocidade.setText(v);
    }

    public void setNConn(String n) {
        this.valueNConn.setText(n);
    }

    public void setTamanho(String t) {
        this.valueTamanho.setText(t);
    }

    public void setTempo(String t) {
        this.valueTempo.setText(t);
    }

    public void setCompleted(int p) {
        this.pBar.setValue(p);
        this.pBar.setString(p + "%");
    }
    
    public void setTempoG(String t) {
        this.valueTempoG.setText(t);
    }
    
    public void setNome(String n) {
        this.valueNome.setText(n);
    }
    
    public void setDownloaded(int index) {
        FragPanel panel = (FragPanel)this.jPanel1;
        panel.setDownloaded(index);
    }
    
    public void setDownloading(int index) {
        FragPanel panel = (FragPanel)this.jPanel1;
        panel.setDownloading(index);
    }
    
    public void setEmpty(int index) {
        FragPanel panel = (FragPanel)this.jPanel1;
        panel.setEmpty(index);        
    }

    /** Creates new form DownloadDetails */
    public DownloadDetails() {
            initComponents();
    }

    public DownloadDetails(IncompleteFile file) {
        this.peers = new peersTableModel();
        parts = ((int)file.getSize())/((int)IncompleteFile.CHUNK_SIZE);
        if(((int)file.getSize())%((int)IncompleteFile.CHUNK_SIZE) != 0) {
            parts++;
        }
        initComponents();
        this.tablePeers.setModel(peers);
        this.pBar.setStringPainted(true);
        this.pBar.setMinimum(0);
        this.pBar.setMaximum(100);         
        this.file = file;
        
        this.setTitle("Download: " + file.getName());
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        mainPanel = new javax.swing.JPanel();
        labelTamanho = new javax.swing.JLabel();
        labelVelocidade = new javax.swing.JLabel();
        labelTempo = new javax.swing.JLabel();
        labelNConn = new javax.swing.JLabel();
        valueTamanho = new javax.swing.JLabel();
        valueVelocidade = new javax.swing.JLabel();
        valueTempo = new javax.swing.JLabel();
        valueNConn = new javax.swing.JLabel();
        labalNome = new javax.swing.JLabel();
        valueNome = new javax.swing.JLabel();
        labelTempoG = new javax.swing.JLabel();
        valueTempoG = new javax.swing.JLabel();
        pBar = new javax.swing.JProgressBar();
        fragPanel = new javax.swing.JPanel();
        jPanel1 = new FragPanel(parts);
        sPanel = new javax.swing.JScrollPane();
        tablePeers = new javax.swing.JTable();

        jToolBar1.setRollover(true);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Info"));

        labelTamanho.setText("Tamanho:");

        labelVelocidade.setText("Velocidade:");

        labelTempo.setText("Tempo Restante:");

        labelNConn.setText("Número de Conexões:");

        valueTamanho.setText("xxxx");

        valueVelocidade.setText("xx Mb/s");

        valueTempo.setText("xx s");

        valueNConn.setText("xx");

        labalNome.setText("Nome:");

        valueNome.setText("xxxx");

        labelTempoG.setText("Tempo Gasto:");

        valueTempoG.setText("xx s");

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pBar, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelTamanho)
                            .addComponent(labelVelocidade)
                            .addComponent(labalNome))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(valueVelocidade, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(valueTamanho, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(valueNome, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(labelNConn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(valueNConn, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE))
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelTempo)
                                    .addComponent(labelTempoG))
                                .addGap(33, 33, 33)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(valueTempoG, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                                    .addComponent(valueTempo, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))))))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(valueTempoG)
                    .addComponent(labelTempoG)
                    .addComponent(labalNome)
                    .addComponent(valueNome))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelTamanho)
                    .addComponent(labelTempo)
                    .addComponent(valueTamanho)
                    .addComponent(valueTempo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelVelocidade)
                    .addComponent(labelNConn)
                    .addComponent(valueVelocidade)
                    .addComponent(valueNConn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        fragPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Fragmentação"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 323, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 27, Short.MAX_VALUE)
        );

        fragPanel.add(jPanel1);

        sPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Conexões Ativas"));

        tablePeers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        sPanel.setViewportView(tablePeers);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(sPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                            .addComponent(fragPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fragPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DownloadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DownloadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DownloadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DownloadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DownloadDetails().setVisible(true);
            }
        });
    }

    private class peersTableModel extends AbstractTableModel {

        private class peer {

            String ip;
            int index;

            public int getIndex() {
                return index;
            }

            public void setIndex(int index) {
                this.index = index;
            }

            public String getIp() {
                return ip;
            }

            public void setIp(String ip) {
                this.ip = ip;
            }

            public peer(String ip, int index) {
                this.ip = ip;
                this.index = index;
            }
        }
        private final ArrayList<peer> items;

        public peersTableModel() {
            this.items = new ArrayList<>();
        }

        @Override
        public String getColumnName(int index) {
            synchronized (items) {
                if (index == 0) {
                    return "Index";
                } else if (index == 1) {
                    return "IP";
                } else {
                    return "Undefined";
                }
            }
        }

        @Override
        public int getRowCount() {
            synchronized (items) {
                return this.items.size();
            }
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (rowIndex < this.items.size()) {
                synchronized (items) {
                    if (columnIndex == 0) {
                        return this.items.get(rowIndex).getIndex() + "";
                    } else if (columnIndex == 1) {
                        return this.items.get(rowIndex).getIp();
                    } else {
                        return null;
                    }
                }
            } else {
                return null;
            }
        }

        public void removeIndex(int index) {
            synchronized (items) {
                for (int i = 0; i < this.items.size(); i++) {
                    if (this.items.get(i).getIndex() == index) {
                        this.items.remove(i);
                        this.fireTableDataChanged();
                        break;
                    }
                }
            }
        }

        public void addItem(int index, String ip) {
            synchronized (items) {
                this.items.add(new peer(ip, index));
            }
            this.fireTableDataChanged();
        }

        public void updateItem(int index, String text) {
            synchronized (items) {
                for (int i = 0; i < this.items.size(); i++) {
                    if (this.items.get(i).getIndex() == index) {
                        this.items.get(i).setIp(text);
                        this.fireTableDataChanged();
                        break;
                    }
                }
            }
        }
    }
    
    private class FragPanel extends JPanel {
        private int nParts;
        private int[] parts;
        
        public FragPanel(int n) {
            this.nParts = n;
            parts = new int[n];
            
            for(int i=0;i<n;i++) {
                parts[i] = 0;
            }
        }
        
        public void setDownloaded(int i) {
            if(i < nParts) {
                parts[i] = 2;
            }
            this.repaint();
        }
        
        public void setDownloading(int i) {
            if(i < nParts) {
                parts[i] = 1;
            }
        }
        
        public void setEmpty(int i) {
            if(i < nParts) {
                parts[i] = 0;
            }
        }
        
        @Override
        public void paintComponent(Graphics context) {
            Graphics2D g = (Graphics2D)context;
            
            int width = this.getWidth();
            int chunkWidth = width/nParts;
            int resto;
            do {
                resto = (nParts*chunkWidth - this.getWidth())/nParts;
                chunkWidth += resto;                
            } while(resto != 0); 
            
            this.setPreferredSize(new Dimension(nParts*chunkWidth,this.getHeight()));
            this.setSize(new Dimension(nParts*chunkWidth,this.getHeight()));

            g.setColor(Color.WHITE);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setBackground(Color.WHITE);
            for(int i=0;i<this.nParts;i++) {
                if(this.parts[i] == 1) {
                    g.setColor(Color.RED);
                    g.fillRect(i*chunkWidth, 0, chunkWidth, this.getHeight());
                } else if(this.parts[i] == 2) {
                    g.setColor(Color.BLUE);
                    g.fillRect(i*chunkWidth, 0, chunkWidth, this.getHeight());
                }
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel fragPanel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel labalNome;
    private javax.swing.JLabel labelNConn;
    private javax.swing.JLabel labelTamanho;
    private javax.swing.JLabel labelTempo;
    private javax.swing.JLabel labelTempoG;
    private javax.swing.JLabel labelVelocidade;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JProgressBar pBar;
    private javax.swing.JScrollPane sPanel;
    private javax.swing.JTable tablePeers;
    private javax.swing.JLabel valueNConn;
    private javax.swing.JLabel valueNome;
    private javax.swing.JLabel valueTamanho;
    private javax.swing.JLabel valueTempo;
    private javax.swing.JLabel valueTempoG;
    private javax.swing.JLabel valueVelocidade;
    // End of variables declaration//GEN-END:variables
}
